// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MainViewModel.cs" company="XamlmNinja">
//   2010
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace ResumableDownload.ViewModel
{
    using System.IO;
    using System.IO.IsolatedStorage;
    using System.Windows.Media.Imaging;
    using GalaSoft.MvvmLight.Messaging;
    using Messages;
    using WP7Contrib.Logging;
    using WP7Contrib.Services.Navigation;

    public class ImageViewModel : ViewModelBaseWp7
    {
        private BitmapImage imageSource;

        public ImageViewModel(INavigationService navigationService, IMessenger messenger, ILog log)
            : base(navigationService, messenger, log)
        {
           this.MessengerInstance.Register<SelectedImageMessage>(this, this.HandleSelectedImageMessage);
        }
        
        public BitmapImage ImageSource
        {
            get { return this.imageSource; }
            set
            {
                this.SetPropertyAndNotify(ref this.imageSource, value, "ImageSource");
            }
        }

        public override void Cleanup()
        {
            base.Cleanup();
        }

        private void HandleSelectedImageMessage(SelectedImageMessage message)
        {
            if (string.IsNullOrEmpty(message.FilePath))
                return;

            var image = new BitmapImage();

            using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            using (var fileStream = myIsolatedStorage.OpenFile(message.FilePath, FileMode.Open, FileAccess.Read))
            {
                image.SetSource(fileStream);
            }

            this.ImageSource = image;
        }
    }
}